/* 
 *  Copyright (C) 2006 James Young
 * `gurumind(a)gmail.com
 * 
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;

namespace IPDEditor
{
    class IPDFieldSBAppData : IPDField
    {
        protected byte sbtype;
        public byte[] appData;

        public IPDFieldSBAppData child;

        public IPDFieldSBAppData(IPDDatabase db)
            : base(db)
        { }

        public string SBType
        {
            get
            {
                if (sbtype == 2)
                    return "BrowserConfig";
                else if (sbtype == 0x10)
                    return "CMIME";
                else if (sbtype == 0)
                    return "IPPP";
                else
                    return "Unknown";
            }
        }

        public override string ToString()
        {
            return "Service Book AppData for " + SBType;
        }

        protected override bool _Read(BinaryReader r)
        {
            if (base._Read(r))
            {
                //sub fields
                subFields = new List<IPDField>();
                MemoryStream ms = new MemoryStream(data);
                BinaryReader br = new BinaryReader(ms);
                sbtype = br.ReadByte();
                appData = br.ReadBytes(data.Length - 1);
                if (sbtype == 2)
                {
                    IPDFieldSBAppDataForBrowser c = new IPDFieldSBAppDataForBrowser(Parent);
                    c.Parse(appData);
                    child = c;
                }
                else
                    child = null;
                br.Close();
                ms.Close();
                return true;
            }
            else
                return false;
        }

        protected override bool _Write(BinaryWriter w, bool englishOnly)
        {
            len = (short)(Length - 3);
            w.Write(len);
            w.Write(type);

            w.Write(sbtype);
            if (sbtype == 2)
            {
                IPDFieldSBAppDataForBrowser c = (IPDFieldSBAppDataForBrowser)child;
                c.Store(w);
            }
            else
                w.Write(appData);
            return true;
        }

        public override short Length
        {
            get
            {
                if (sbtype == 2)
                {
                    IPDFieldSBAppDataForBrowser c = (IPDFieldSBAppDataForBrowser)child;
                    return (short)(3 + 1 + c.Length);
                }
                else
                    return (short)(3 + 1 + appData.Length);
            }
        }

        protected virtual byte[] ToBinary()
        {
            throw new NotImplementedException("AppData base class not support ToBinary.");
        }
    }
}
